<template>
  <view
    class="page_root"
    data-page-name="工单-新建/编辑组件"
    data-page-identification="d_opbd1fu1bi"
  >
    <!-- UNI_APP_EXEGESIS_START NAVIGATION_TEMPLATE UNI_APP_EXEGESIS_END -->
    <!-- begin vid_lshifg44co 自定义模板_62j9cv4p05 -->
    <u-navbar
      back-icon-color="#fff"
      :title="mode === 'add' ? '新建工单' : '编辑工单'"
      title-color="#fff"
      :border-bottom="false"
    >
      <template #right>
        <view class="right-icon" @click="handleShowAddOrEdit({})"></view>
      </template>
    </u-navbar>
    <!-- 筛选 -->
    <u-mask :show="state.loading">
      <view class="warp">
        <view class="rect" @tap.stop>附件上传中....</view>
      </view>
    </u-mask>
    <view class="add-or-edit-wrapper">
      <view class="form-title">工单基本信息</view>
      <view class="form-body" scroll-y>
        <u-form ref="formRef" :model="state.modalForm" :rules="rules" label-position="top">
          <u-form-item label="工单标题" prop="content" required>
            <u-input
              v-model="state.modalForm.content"
              type="textarea"
              maxlength="100"
              show-word-limit
              placeholder="请输入工单标题"
              border
            />
          </u-form-item>

          <u-form-item label="工单类型" prop="type" required>
            <u-input
              v-model="state.modalForm.type"
              readonly
              type="select"
              placeholder="请选择"
              border
              @click="showPicker('type')"
            />
            <u-popup v-model="show.type" mode="bottom">
              <van-picker
                :columns-field-names="{ text: 'label', value: 'value' }"
                :columns="state.workTypeList"
                @confirm="onConfirm('type', $event)"
                @cancel="show.type = false"
              />
            </u-popup>
          </u-form-item>

          <u-form-item label="优先级" prop="priority" required>
            <u-input
              v-model="state.modalForm.priority"
              readonly
              type="select"
              placeholder="请选择"
              border
              @click="showPicker('priority')"
            />
            <van-popup v-model:show="show.priority" position="bottom">
              <van-picker
                :columns-field-names="{ text: 'label', value: 'value' }"
                :columns="[
                  { label: 'p0', value: 'p0' },
                  { label: 'p1', value: 'p1' },
                  { label: 'p2', value: 'p2' },
                  { label: 'p3', value: 'p3' },
                ]"
                @confirm="onConfirm('priority', $event)"
                @cancel="show.priority = false"
              />
            </van-popup>
          </u-form-item>

          <u-form-item label="计划解决时长（小时）" prop="workHours">
            <u-input v-model="state.modalForm.workHours" type="number" placeholder="请输入" border>
            </u-input>
          </u-form-item>

          <u-form-item label="计划解决时间" prop="endTime" required>
            <u-input
              v-model="state.modalForm.endTime"
              readonly
              type="select"
              placeholder="请选择计划解决时间"
              border
              @click="showPicker('endTime')"
            />
            <van-popup v-model:show="show.endTime" position="bottom">
              <u-picker
                mode="time"
                v-model="show.endTime"
                :params="{
                  year: true,
                  month: true,
                  day: true,
                  hour: true,
                  minute: true,
                  second: true,
                }"
                @confirm="onConfirm('endTime', $event)"
                @cancel="show.endTime = false"
              ></u-picker>
            </van-popup>
          </u-form-item>

          <u-form-item label="问题来源" prop="questionSource" required>
            <u-input
              v-model="state.modalForm.questionSource"
              readonly
              type="select"
              placeholder="请选择"
              border
              @click="showPicker('questionSource')"
            />
            <van-popup v-model:show="show.questionSource" position="bottom">
              <van-picker
                :columns-field-names="{ text: 'label', value: 'value' }"
                :columns="state.wtlyList"
                @confirm="onConfirm('questionSource', $event)"
                @cancel="show.questionSource = false"
              />
            </van-popup>
          </u-form-item>

          <u-form-item label="所属区域" prop="areaCode" required>
            <u-input
              v-model="state.modalForm.areaName"
              readonly
              type="select"
              placeholder="请选择"
              border
              @click="showPicker('areaCode')"
            />
            <van-popup v-model:show="show.areaCode" position="bottom">
              <van-picker
                :columns-field-names="{ text: 'label', value: 'value' }"
                :columns="state.areaList"
                @confirm="onConfirm('areaCode', $event)"
                @cancel="show.areaCode = false"
              />
            </van-popup>
          </u-form-item>

          <u-form-item label="所属客户" prop="customer" required>
            <u-input
              v-model="state.modalForm.customer"
              readonly
              type="select"
              placeholder="请选择"
              border
              @click="showPicker('customer')"
            />
            <van-popup v-model:show="show.customer" position="bottom">
              <van-picker
                :columns-field-names="{ text: 'label', value: 'value' }"
                :columns="state.customList"
                @confirm="onConfirm('customer', $event)"
                @cancel="show.customer = false"
              />
            </van-popup>
          </u-form-item>

          <u-form-item label="所属项目" prop="projectId" required>
            <u-input
              v-model="state.modalForm.projectName"
              readonly
              type="select"
              placeholder="请选择"
              border
              @click="showPicker('projectId')"
            />
            <van-popup v-model:show="show.projectId" position="bottom">
              <van-picker
                :columns-field-names="{ text: 'label', value: 'value' }"
                :columns="state.projectList"
                @confirm="onConfirm('projectId', $event)"
                @cancel="show.projectId = false"
              />
            </van-popup>
          </u-form-item>

          <u-form-item label="项目阶段">
            <u-input
              v-model="state.modalForm.milepostName"
              readonly
              type="select"
              placeholder="请选择"
              border
              @click="showPicker('milepostId')"
            />
            <van-popup v-model:show="show.milepostId" position="bottom">
              <van-picker
                :columns-field-names="{ text: 'label', value: 'value' }"
                :columns="state.milepostList"
                @confirm="onConfirm('milepostId', $event)"
                @cancel="show.milepostId = false"
              />
            </van-popup>
          </u-form-item>

          <u-form-item label="环境">
            <u-input
              v-model="state.modalForm.environment"
              readonly
              type="select"
              placeholder="请选择"
              border
              @click="showPicker('environment')"
            />
            <van-popup v-model:show="show.environment" position="bottom">
              <van-picker
                :columns-field-names="{ text: 'label', value: 'value' }"
                :columns="state.environmentList"
                @confirm="onConfirm('environment', $event)"
                @cancel="show.environment = false"
              />
            </van-popup>
          </u-form-item>

          <u-form-item label="所属产品">
            <u-input
              v-model="state.modalForm.production"
              readonly
              type="select"
              placeholder="请选择"
              border
              @click="showPicker('production')"
            />
            <van-popup v-model:show="show.production" position="bottom">
              <van-picker
                :columns-field-names="{ text: 'label', value: 'value' }"
                :columns="state.productList"
                @confirm="onConfirm('production', $event)"
                @cancel="show.production = false"
              />
            </van-popup>
          </u-form-item>

          <u-form-item label="版本">
            <u-input v-model="state.modalForm.version" readonly border />
          </u-form-item>

          <u-form-item label="告警级别">
            <u-input
              v-model="state.modalForm.warningLevel"
              readonly
              type="select"
              placeholder="请选择"
              border
              @click="showPicker('warningLevel')"
            />
            <van-popup v-model:show="show.warningLevel" position="bottom">
              <van-picker
                :columns-field-names="{ text: 'label', value: 'value' }"
                :columns="state.warnList"
                @confirm="onConfirm('warningLevel', $event)"
                @cancel="show.warningLevel = false"
              />
            </van-popup>
          </u-form-item>

          <u-form-item label="解决人">
            <u-input
              v-model="state.modalForm.solverList"
              readonly
              type="select"
              placeholder="请选择"
              border
              @click="showPicker('solverList')"
            />

            <van-popup v-model:show="show.solverList" position="bottom">
              <van-picker
                :columns-field-names="{ text: 'label', value: 'value' }"
                :columns="state.allUser"
                @confirm="onConfirm('solverList', $event)"
                @cancel="show.solverList = false"
              />
            </van-popup>
          </u-form-item>

          <view class="upload-field">
            <view class="label">上传附件</view>
            <view class="uploader-wrapper" @click.stop>
              <van-uploader
                v-model="state.modalForm.descriptionAttachmentList"
                multiple
                :after-read="handlerFatherUpload"
                :before-delete="handlerFatherRemove"
                accept="*/*"
                :preview-image="false"
                :preview-full-image="false"
              >
                <van-button icon="plus" type="primary">上传文件</van-button>
              </van-uploader>
              <!-- 自定义文件列表 -->
              <div class="custom-file-list">
                <div
                  v-for="file in state.modalForm.descriptionAttachmentList"
                  :key="file.uid"
                  class="file-item"
                >
                  <!-- 图片文件显示预览图 -->
                  <div v-if="file.isImage" class="file-preview" @click="previewImage(file)">
                    <img :src="file.url" :alt="file.name" class="preview-image" />
                    <div class="file-overlay">
                      <van-icon name="eye-o" size="16" color="#fff" />
                    </div>
                  </div>

                  <!-- 非图片文件显示图标 -->
                  <div v-else class="file-icon" @click="downloadFile(file)">
                    <div class="icon-wrapper">
                      <span class="file-type-icon">{{ getFileIcon(file) }}</span>
                      <van-icon name="down" size="14" color="#1989fa" class="download-icon" />
                    </div>
                  </div>

                  <!-- 文件信息 -->
                  <div class="file-info">
                    <div class="file-name van-ellipsis">{{ file.name }}</div>
                    <div class="file-size">{{ formatFileSize(file.size) }}</div>
                  </div>

                  <!-- 删除按钮 -->
                  <van-button
                    size="small"
                    type="danger"
                    plain
                    @click="removeFile(file)"
                    class="delete-btn"
                  >
                    删除
                  </van-button>
                </div>
              </div>
            </view>
          </view>

          <view class="editor-wrap">
            <view class="label">问题描述</view>
            <view id="quillEditor" class="quill-editor" ref="quillInstance"></view>
          </view>
        </u-form>
      </view>
      <view class="footer-bar">
        <van-button class="cancel-btn" @click="onCancel" icon="cross" plain>取消</van-button>
        <van-button
          :loading="state.fatherLoading"
          @click="submit"
          :style="{
            backgroundImage: 'linear-gradient(-75deg, #82B0FF 0%, #3366FF 74%)',
            border: 'none',
            color: '#fff',
          }"
          icon="completed"
        >
          {{ state.fatherLoading ? '提交中...' : '提交' }}
        </van-button>
      </view>
      <!-- 底部操作栏 -->
    </view>
    <!-- end vid_lshifg44co 自定义模板_62j9cv4p05 -->
  </view>
</template>
<script setup>
  import {
    ref,
    reactive,
    toRaw,
    markRaw,
    watch,
    computed,
    onBeforeMount,
    onMounted,
    onBeforeUnmount,
    onUnmounted,
    onActivated,
    onDeactivated,
    getCurrentInstance,
  } from 'vue';
  import { useRoute } from 'vue-router';
  const route = useRoute();
  import { get, post, put, del, request, requestWithHeaders } from '@/utils/http/Axios';
  import {
    cloneDeep,
    localGet,
    traversalTreeStructure,
    set,
    checkCaseCondition,
    throttle,
    merge,
    debounce,
    getGridStyle,
    getCellRenderAble,
    formulaStrategy,
    getApplicationId,
    getComponentParamsValue,
    get as lodashGet,
  } from '@/utils/index';
  import {
    isEqual,
    isNullOrEmpty,
    isEmptyArr,
    isArray,
    isEmpty,
    isNullOrUnDef,
    isContained,
  } from '@/utils/is';
  import { CovertOptions, getChartsDataSourceConvert } from '@/utils/chart';
  import {
    propertyFormatByNumber,
    propertyFormatByPercentage,
    propertyFormatByDate,
    parseSubFromDataList,
  } from '@/utils/format';
  import { checkCommonCondition, getResultByCurrentCommonCondition } from '@/utils/formCondition';
  import { FormFormat } from '@/utils/formFormat';
  import { customAddWaterMarkFunc, generateWaterMarkText } from '@/utils/addWaterMark';
  import dayjs from 'dayjs';
  import hashSum from 'hash-sum';
  import {
    onPullDownRefresh,
    onLoad,
    onReady,
    onShow,
    onHide,
    onPageScroll,
    onUnload,
  } from '@dcloudio/uni-app';
  /*** UNI_APP_EXEGESIS ***
  import { handleRedirect, permission, parseJson } from '@/utils/common';
  import { onPullDownRefresh, onLoad, onReady, onShow, onHide, onPageScroll, onUnload } from '@dcloudio/uni-app';
  import { BroadcastMessage } from '@/utils/BroadcastMessage';
  import { sendToken } from "@/hooks/useIframeToken";
  *** UNI_APP_EXEGESIS ***/

  // ---------------------------- 属性定义 ----------------------------
  const sourceId = 'page3000001236';

  // 获取传入的流程ID和组件参数
  const props = defineProps({
    processInstanceId: {
      type: [String, Number, Boolean],
      default: undefined,
    },
    hideNav: {
      type: [Boolean],
      default: undefined,
    },
    type: {
      type: [String],
      default: undefined,
    },
    editForm: {
      type: [Object],
      default: undefined,
    },
    visible: {
      type: [Boolean],
      default: undefined,
    },
  });

  // 组件参数默认值
  const componentParamsDefaultProps = {
    type: getComponentParamsValue(undefined),
    editId: getComponentParamsValue(undefined),
  };

  // 是否显示菜单按钮
  const isMenuIconShow = false;
  // NAVIGATION_MENU
  const handleShowNavigation = () => {};

  let isProcessState = ref(false);

  const setTimeOutList = [];

  const vid_lshifg44co_props = reactive({
    code: '',
  });

  // ============================ 属性定义 ============================

  // ---------------------------- 元素数据引用 ----------------------------
  // 组件 自定义模板_62j9cv4p05 ref 的引用
  const vid_lshifg44co_ref = ref(null);
  // 动态key的map
  const fieldTypeMap = {};
  // 动态key的map
  const refMap = { vid_lshifg44co_ref };

  const showState = reactive({
    vid_lshifg44co_visible: true,
  });
  // ============================ 元素数据引用 ============================

  // ---------------------------- 数据 ----------------------------

  // ============================ 数据 ============================

  // ---------------------------- 方法 ----------------------------
  // ---------------------------- 页面数据 ----------------------------

  // ============================ 页面数据 ============================

  // ---------------------------- 数据字典 ----------------------------

  // ============================ 数据字典 ============================

  // ---------------------------- 响应 ----------------------------

  // ============================ 响应 ============================

  // ---------------------------- 函数 ----------------------------

  // 自定义函数 返回上一页
  const customFunction_goBack_2vlk9y2wgn = (params) => {
    uni.navigateBack();
  };

  // ============================ 函数 ============================

  // ---------------------------- 页面参数 ----------------------------

  const pageParameter_state = reactive({
    processInstanceId: undefined,
  });

  // ============================ 页面参数 ============================

  // ---------------------------- 组件事件处理方法 ----------------------------

  // ============================ 组件事件处理方法 ============================

  // ============================ 方法 ============================

  // ---------------------------- 生命周期 ----------------------------
  /*** UNI_APP_EXEGESIS ***
      // 获取上一层传递的数据
      const workflowChannel = new BroadcastMessage('WORKFLOW');
      workflowChannel.publish({ status: 'Ready' });
      workflowChannel.subscribe((data) => {
        if (data) {
          isProcessState.value = (window.self !== window.parent && data.type === 'hideHeader');
        }
      });
      *** UNI_APP_EXEGESIS ***/

  const pageScrollTop = ref(0);

  // *** PREVIEW_EXEGESIS ***
  onMounted(() => {
    setPageParams(route.query);
    // 设置表单的rule
    try {
    } catch {
      // do nothing
    }
  });
  // *** PREVIEW_EXEGESIS *** //

  /*** UNI_APP_EXEGESIS ***
  const routeOption = ref({})
  onLoad((option) => {
    routeOption.value = option;
  });
  onReady(() => {
    setPageParams(routeOption.value)
    // 设置表单的rule
    try{

    }catch{
        // do nothing
    }
  });
  // 图表刷新标记
  const uChartsReshowFlag = ref(false);
  onHide(() => { // 页面隐藏后标记置为false(如果不置为false无法触发图表更新)
      uChartsReshowFlag.value = false
  })
  onShow(() => {
      uChartsReshowFlag.value = true; // 页面激活后,标记置为true

      setPageParams(routeOption.value)
  })
  onPageScroll(e => {
      pageScrollTop.value = e.scrollTop
  });
  *** UNI_APP_EXEGESIS ***/

  let setPageParams = (routerParam) => {
    const pageParams = [{ dataType: 'STRING', name: 'processInstanceId' }];
    const strategyMap = {
      STRING: (param, paramValue) => {
        pageParameter_state[param.name] = paramValue;
      },
      BOOLEAN: (param, paramValue) => {
        if ('true' === (paramValue || '').toLowerCase()) {
          pageParameter_state[param.name] = true;
        } else if ('false' === (paramValue || '').toLowerCase()) {
          pageParameter_state[param.name] = false;
        } else {
          // TODO: 是否要支持toast
          console.error('参数传入错误！类型不匹配！');
        }
      },
      NUMBER: (param, paramValue) => {
        if (!isNaN(paramValue)) {
          pageParameter_state[param.name] = Number(paramValue);
        } else {
          // TODO: 是否要支持toast
          console.error('参数传入错误！类型不匹配！');
        }
      },
      ARRAY: (param, paramValue) => {
        if (isNullOrUnDef(paramValue) || !paramValue || paramValue === 'undefined') {
          // default value
          pageParameter_state[param.name] = [];
        } else if (paramValue.trim().startsWith('[') && paramValue.trim().endsWith(']')) {
          try {
            pageParameter_state[param.name] = JSON.parse(decodeURI(paramValue));
          } catch (error) {
            console.error('参数解析失败 ', error);
          }
        } else {
          console.error('参数传入错误！类型不匹配！');
        }
      },
    };
    pageParams.forEach((param) => {
      strategyMap[param.dataType](param, routerParam[param.name]);
    });
  };

  onUnmounted(() => {
    // 销毁定时器
    setTimeOutList.forEach(({ repeat, timer }) => {
      repeat ? clearInterval(timer) : clearTimeout(timer);
    });
  });

  /*** UNI_APP_EXEGESIS ***
  onPullDownRefresh(() => {
    // 下拉刷新
    setTimeout(() => {
        uni.stopPullDownRefresh()
    }, 1000)
  })
  *** UNI_APP_EXEGESIS ***/

  // ============================ 生命周期 ============================

  // ---------------------------- 数据关联处理 ----------------------------
  // ---------------------------- 组件数据同步 ----------------------------

  // ============================ 组件数据同步 ============================
  //
  // ============================ 数据关联处理 ============================

  // ---------------------- 不同组件自定义的处理逻辑 ---------------------

  // ====================== 不同组件自定义的处理逻辑 ======================

  // ================================定制化逻辑========================================

  import 'vant/lib/index.css';
  const mode = ref('add');
  const editForm = ref({});
  onLoad((options) => {
    mode.value = options.mode || 'add';

    if (mode.value === 'edit') {
      const savedForm = uni.getStorageSync('edit_form');

      if (savedForm) {
        editForm.value = savedForm;
        currentData.value = savedForm;
        Object.assign(state.modalForm, {
          ...savedForm,
          descriptionAttachmentList: savedForm.descriptionAttachmentList || [],
        });
        state.modalForm.solverList = savedForm.solver;
        nextTick(() => {
          get(`/solution-ppm-work-order/api/v1/work_order/details/${savedForm.id}`).then((data) => {
            let descriptionData = JSON.parse(data.data.workOrderDto.description);
            quillEditor.value.setContents(descriptionData);
          });
        });
      }
    }
  });
  onMounted(() => {
    formRef?.value?.setRules(rules);
    getAllUser();
    getPmName();
    getPmo();
    getAreaList();
    getCustomerList();
    getWorkType();
    getWarnList();
    getWtly();
    getClassfy();
    setPageStyle();
  });
  function setPageStyle(newClass) {
    // #ifdef H5
    // 仅在 H5 执行
    const appDiv = document.querySelector('#app');
    if (appDiv) {
      appDiv.className = '';

      // 再添加当前需要的类
      if (newClass) {
        appDiv.classList.add(newClass);
      }
    }

    const topHeader = document.querySelector('.uni-page-head');
    if (topHeader) topHeader.remove();

    const wrapper = document.querySelector('uni-page-wrapper');
    if (wrapper) wrapper.style.height = '100%';
    const pageRoot = document.querySelector('.page_root');
    console.log(pageRoot);

    // #endif

    // #ifdef MP
    // 小程序端执行（如果你要做兼容逻辑，可以写这里）
    console.log('当前是小程序环境，不需要处理头部或背景');
    // #endif
  }
  import { nextTick } from 'vue';
  const state = reactive({
    filter: {
      type: undefined,
      monitorScene: undefined,
      priority: undefined,
      questionSource: undefined,
      status: '',
      timeout: undefined,
      keyWords: undefined,
      number: undefined,
      factoryCode: undefined,
      production: undefined,
      pmName: undefined,
      pmoName: undefined,
      environment: undefined,
      createdByName: undefined,
      solverName: undefined,
      factoryType: undefined,
      rootCauseClassify: undefined,
      createdTimeList: [],
      projectIdList: [],
    },
    activeKey: "''",
    tableHeight: 400,
    treeData: [],
    tagList: [],
    statusList: [
      {
        label: '未开始',
        value: '未开始',
      },
      {
        label: '解决中',
        value: '解决中',
      },
      {
        label: '已解决',
        value: '已解决',
      },
      {
        label: '已关闭',
        value: '已关闭',
      },
      {
        label: '已回访',
        value: '已回访',
      },
    ],
    changeStausList: [
      {
        label: '正在处理',
        value: '正在处理',
      },
      {
        label: '已解决',
        value: '已解决',
      },
      {
        label: '无需解决',
        value: '无需解决',
      },
      {
        label: '申请流转',
        value: '申请流转',
      },
    ],
    changeHaveSonStausList: [],
    dataList: [],
    collapseKey: [],
    addOrEditVisible: false,
    modalTitle: '',
    modalForm: {
      content: undefined,
      type: undefined,
      priority: undefined,
      questionSource: undefined,
      monitorScene: undefined,
      workHours: undefined,
      endTime: undefined,
      areaCode: undefined,
      areaName: undefined,
      projectId: undefined,
      projectName: undefined,
      milepostId: undefined,
      milepostName: undefined,
      taskId: undefined,
      taskName: undefined,
      version: undefined,
      warningLevel: undefined,
      customer: undefined,
      production: undefined,
      environment: undefined,
      description: undefined,
      solverList: [],
      descriptionAttachmentList: [],
      qillData: '',
    },
    fatherLoading: false,
    loading: false,
    sonLoading: false,
    editSonVisible: false,

    deleteLoading: false,
    fileVisible: false,
    remarkVisible: false,
    remarks: '',
    changeHaveSonStatusVisible: false,
    changeStatusForm: {
      status: undefined,
      reason: '',
      attachmentList: [],
      workOrderId: undefined,
      solution: undefined,
    },

    deleteVisible: false,
    areaList: [],
    projectList: [],
    milepostList: [],
    taskList: [],
    customList: [],
    environmentList: [],
    searchEnvironmentList: [],
    productList: [],
    allUser: [],
    warnList: [],
    wtlyList: [],
    pmoList: [],
    pmNameList: [],
    previewImage: '',
    previewVisible: false,
    // 工单类型
    workTypeList: [],
    monitorSceneList: [],
  });
  //    新需求
  const newState = reactive({
    changeStatusLoading: false,
    isExpandAll: false,
    circulationVisible: false,
    resolvingVisible: false,
    resolvedVisible: false,
    circulationForm: {
      solverList: [],
      status: '流转',
    },
    resolvingForm: {
      solution: '',
      status: '解决中',
    },
    resolvedForm: {
      solution: '',
      attachmentList: [],
      status: '已解决',
      solutionDetail: '',
    },
    closeForm: {
      status: '关闭',
    },
    workOrderId: undefined,
  });
  const currentData = ref({});

  const formRef = ref(null);
  const rules = {
    content: [{ required: true, message: '请输入工单标题', trigger: ['blur', 'change'] }],
    type: [{ required: true, message: '请选择工单类型', trigger: ['blur', 'change'] }],
    workHours: [
      {
        required: false,
        validator: validateWorkingHours,
        trigger: ['blur', 'input', 'change'],
      },
    ],
    priority: [{ required: true, message: '请选择优先级', trigger: ['blur', 'change'] }],
    endTime: [
      {
        required: true,
        message: '请选择计划解决时间',
        trigger: ['blur', 'change'],
      },
    ],
    questionSource: [
      {
        required: true,
        message: '请选择问题来源',
        trigger: ['blur', 'change'],
      },
    ],
    areaCode: [
      {
        required: true,
        message: '请选择所属区域',
        trigger: ['blur', 'change'],
      },
    ],
    customer: [
      {
        required: true,
        message: '请选择所属客户',
        trigger: ['blur', 'change'],
      },
    ],
    projectId: [
      {
        type: 'number',
        required: true,
        message: '请选择所属项目',
        trigger: ['blur', 'change'],
      },
    ],
  };
  function validateWorkingHours(rule, val, callback) {
    if (!val) {
      callback(); // 允许为空，校验通过
    } else if (/^(0(\.5)?|[1-9](\d*)?(\.5)?(\.0)?)$/.test(val)) {
      callback();
    } else {
      callback(new Error('请输入合法的工时数，支持0.5倍数'));
    }
  }

  // 按需导入 Vant 3 组件
  import { Form, Field, CellGroup, Picker, Popup, Uploader, Button, DatePicker, Toast } from 'vant';
  // 页面内注册 Vant 组件
  const { appContext } = getCurrentInstance();
  [
    ['van-form', Form],
    ['van-field', Field],
    ['van-cell-group', CellGroup],
    ['van-picker', Picker],
    ['van-popup', Popup],
    ['van-uploader', Uploader],
    ['van-button', Button],
    ['van-date-picker', DatePicker],
  ].forEach(([name, comp]) => appContext.app.component(name, comp));
  import 'vant/lib/index.css';
  import Quill from 'quill';
  import '@vueup/vue-quill/dist/vue-quill.snow.css';
  import 'quill/dist/quill.snow.css';
  const minDate = new Date();
  const show = reactive({
    type: false,
    priority: false,
    endTime: false,
    areaCode: false,
    questionSource: false,
    customer: false,
    environment: false,
    production: false,
    milepostId: false,
    projectId: false,
    taskId: false,
    warningLevel: false,
    solverList: false,
  });
  // Picker 确认事件
  function onConfirm(type, val) {
    // 普通 picker（非日期）
    if (['projectId', 'milepostId', 'taskId'].includes(type)) {
      const selected = val.selectedOptions?.[0];
      if (selected) {
        state.modalForm[`${type.replace('Id', '')}Name`] = selected.label; // 中文展示名
        state.modalForm[type] = selected.value; // 真正的 id
      }
    } else if (type === 'areaCode') {
      const selected = val.selectedOptions?.[0];
      if (selected) {
        state.modalForm.areaName = selected.label; // 中文展示名
        state.modalForm.areaCode = selected.value; // 真正的 id
      }
    } else if (type === 'endTime') {
      let dateStr = `${val.year}-${val.month}-${val.day} ${val.hour}:${val.minute}:${val.second}`;
      console.log(val);

      state.modalForm.endTime = dateStr;
    } else if (type === 'solverList') {
      const selected = val.selectedOptions?.[0];
      if (selected) {
        state.modalForm.solverList = selected.label;
      }
    } else {
      state.modalForm[type] = val.selectedValues[0];
    }
    // Picker 确认事件续写
    show[type] = false;
    switch (type) {
      case 'areaCode':
        areaChange();
        break;
      case 'projectId':
        projectChange();
        break;
      case 'customer':
        customerChange();
        break;
      case 'environment':
        environmentChange();
        break;
      case 'production':
        productChange();
        break;
      case 'milepostId':
        milepostChange();
        break;
      case 'taskId':
        break;
      case 'priority':
        getSolveTimeByType(state.modalForm.priority);
        break;
      case 'endTime':
        break;
      default:
        state.modalForm[type] = val.selectedValues[0] || val.text;
    }
    // ✅ 手动触发表单校验
  }
  //     计算解决时间
  function getSolveTime() {
    // 获取当前时间
    let currentDate = dayjs();
    let num = state.modalForm.workHours;
    // 计算新时间
    let newDate = currentDate.add(num, 'hour');

    // 格式化新时间为 "YYYY-MM-DD HH:mm" 格式
    let formattedDate = newDate.format('YYYY-MM-DD HH:mm:ss');

    state.modalForm.endTime = formattedDate;
  }
  //     根据类型获取解决时间
  function getSolveTimeByType(type) {
    let num = 0;
    if (type == 'p0') {
      num = 4;
      state.modalForm.workHours = 4;
    } else if (type == 'p1') {
      num = 24;
      state.modalForm.workHours = 24;
    } else if (type == 'p2') {
      num = 96;
      state.modalForm.workHours = 96;
    } else if (type == 'p3') {
      num = 48;
      state.modalForm.workHours = 336;
    }
    getSolveTime();
  }
  // 显示 Picker
  function showPicker(type) {
    show[type] = true;
    if (type === 'customer') {
      getCustomerList();
    } else if (type === 'environment') {
      getEnvironmentList();
    } else if (type === 'production') {
      getProductList();
    } else if (type === 'projectId') {
      getProjectList();
    } else if (type === 'milepostId') {
      getMilepostList();
    } else if (type === 'taskId') {
      getTaskList();
    }
  }

  // function downloadFile(url, filename) {
  //   console.log('来了');

  //   // 创建临时a标签触发浏览器下载
  //   const link = document.createElement('a');
  //   link.href = url;
  //   link.download = filename || 'file';
  //   document.body.appendChild(link);
  //   link.click();
  //   document.body.removeChild(link);
  // }
  async function handlerFatherUpload(files) {
    if (state.fatherLoading) return;
    state.fatherLoading = true;
    state.loading = true;

    try {
      // 🧩 转成数组
      const fileList = Array.isArray(files) ? files : [files];

      // ⚙️ 先过滤掉 base64 临时文件
      state.modalForm.descriptionAttachmentList = state.modalForm.descriptionAttachmentList.filter(
        (f) => f.url && !f.url.startsWith('blob:'),
      );

      for (const item of fileList) {
        const rawFile = item.file || item;

        const formData = new FormData();
        formData.append('file', rawFile);

        const res = await fetch('/file-storage/api/v1/file/upload', {
          method: 'POST',
          body: formData,
        });

        const data = await res.json();
        if (!res.ok || !data?.data?.fullUrl) throw new Error(data?.message || '上传失败');

        const fullUrl = data.data.fullUrl;

        const newFile = {
          uid: rawFile.uid || `${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
          name: rawFile.name,
          size: rawFile.size,
          type: rawFile.type,
          status: 'done',
          url: fullUrl,
          isImage: isImageFile(rawFile),
        };

        // ✅ 避免重复添加
        if (
          !state.modalForm.descriptionAttachmentList.some(
            (f) => f.url === fullUrl || f.name === newFile.name,
          )
        ) {
          state.modalForm.descriptionAttachmentList.push(newFile);
        }
      }

      showSuccessToast('上传成功');
    } catch (err) {
      console.error('上传异常', err);
      showFailToast(err.message || '上传异常');
    } finally {
      state.fatherLoading = false;
      state.loading = false;
    }

    return false;
  }

  function isImageFile(file) {
    // 简单判断 mime 类型是否以 image/ 开头
    return file.type
      ? file.type.startsWith('image/')
      : /\.(jpg|jpeg|png|gif|bmp|webp)$/i.test(file.name);
  }
  import { showImagePreview, showToast } from 'vant';
  // 图片预览
  function previewImage(file) {
    if (!file.url) {
      showFailToast('预览图片地址无效');
      return;
    }

    const images = state.modalForm.descriptionAttachmentList
      .filter((f) => f.isImage && f.url)
      .map((f) => f.url);

    const currentIndex = images.findIndex((url) => url === file.url);

    showImagePreview({
      images,
      startPosition: Math.max(currentIndex, 0),
      closeable: true,
    });
  }

  // 文件下载
  // 最简单的移动端解决方案
  function downloadFile(file) {
    if (!file.url) {
      showFailToast('下载文件地址无效');
      return;
    }
    showSuccessToast('文件已打开，请手动保存');
    // 直接在新窗口打开，让用户手动保存
    window.open(file.url, '_blank');
  }
  // 删除文件
  function removeFile(file) {
    state.modalForm.descriptionAttachmentList = state.modalForm.descriptionAttachmentList.filter(
      (item) => item.uid !== file.uid,
    );
    showSuccessToast('文件已删除');
  }

  // 获取文件图标
  function getFileIcon(file) {
    if (!file) return '📎';

    if (file.icon) return file.icon;

    const fileName = file.name || '';
    const fileType = file.type || '';

    if (file.isImage) return '🖼️';
    if (/\.(pdf)$/i.test(fileName)) return '📄';
    if (/\.(doc|docx)$/i.test(fileName)) return '📝';
    if (/\.(xls|xlsx)$/i.test(fileName)) return '📊';
    if (/\.(zip|rar|7z)$/i.test(fileName)) return '📦';
    if (/\.(txt|md)$/i.test(fileName)) return '📃';
    if (fileType.startsWith('video/')) return '🎬';
    if (fileType.startsWith('audio/')) return '🎵';

    return '📎';
  }

  // 格式化文件大小
  function formatFileSize(bytes) {
    if (!bytes) return '0 B';

    const units = ['B', 'KB', 'MB', 'GB'];
    let size = bytes;
    let unitIndex = 0;

    while (size >= 1024 && unitIndex < units.length - 1) {
      size /= 1024;
      unitIndex++;
    }

    return `${size.toFixed(1)} ${units[unitIndex]}`;
  }
  // 父移除文件
  function handlerFatherRemove(file) {
    state.modalForm.descriptionAttachmentList = state.modalForm.descriptionAttachmentList.filter(
      (item) => item.uid !== file.uid,
    );
  }

  // 将 dataURL 转换为 File 对象的辅助函数
  const dataURLtoFile = (dataurl, filename) => {
    const arr = dataurl.split(',');
    const mime = arr[0].match(/:(.*?);/)[1];
    const bstr = atob(arr[1]);
    let n = bstr.length;
    const u8arr = new Uint8Array(n);
    while (n--) {
      u8arr[n] = bstr.charCodeAt(n);
    }
    return new File([u8arr], filename, { type: mime });
  };
  // 上传api
  const uploadFileAPI = async (file) => {
    // 构造 FormData
    const formData = new FormData();
    formData.append('file', file.file || file.originFileObj || file);

    // 打印验证一下
    for (let [key, value] of formData.entries()) {
      console.log('FormData内容:', key, value);
    }

    try {
      const res = await fetch('/file-storage/api/v1/file/upload', {
        method: 'POST',
        body: formData, // ✅ 真正传文件流
        // ⚠️ 不要手动设置 Content-Type，让浏览器自动加 boundary
        // headers: { 'Content-Type': 'multipart/form-data' }, ❌
      });

      if (!res.ok) {
        throw new Error(`上传失败: ${res.status}`);
      }

      const data = await res.json();
      console.log('上传返回:', data);

      // 按你之前接口结构封装返回
      return { data: { fullUrl: data.data.fullUrl } };
    } catch (err) {
      console.error('上传图片出错:', err);
      throw err;
    }
  };

  // 子组件

  const quillInstance = null;
  const isQuillReady = ref(false);

  onMounted(async () => {
    await nextTick();
    setTimeout(() => {
      initQuill();
    }, 300);
  });

  onUnmounted(() => {
    // destroyQuill();
  });

  // 自定义图片处理函数
  async function initQuill() {
    const el = document.getElementById('quillEditor');

    if (!el) {
      console.error('❌ 编辑器元素未找到');
      return;
    }

    try {
      quillEditor.value = new Quill(el, {
        modules: {
          toolbar: {
            container: [
              [{ size: ['small', false, 'large', 'huge'] }],
              ['bold', 'italic', 'underline'],
              [{ color: [] }],
              ['clean', 'image'],
            ],
            handlers: {
              image: imageHandler,
            },
          },
          clipboard: true,
        },
        theme: 'snow',
      });

      isQuillReady.value = true;
      console.log('✅ Quill 初始化成功');
    } catch (error) {
      console.error('❌ Quill 初始化失败:', error);
      isQuillReady.value = false;
    }
  }
  function imageHandler() {
    const input = document.createElement('input');
    input.setAttribute('type', 'file');
    input.setAttribute('accept', 'image/*');
    input.style.display = 'none';

    input.addEventListener('change', async () => {
      const file = input.files[0];
      if (file) {
        // 在这里处理图片上传
        console.log('选择的文件:', file);

        // 模拟上传过程
        const reader = new FileReader();
        reader.onload = (e) => {
          // 获取当前光标位置
          const range = quillEditor.value.getSelection();
          // 插入图片
          quillEditor.value.insertEmbed(range.index, 'image', e.target.result);
        };
        reader.readAsDataURL(file);
      }

      // 清理
      document.body.removeChild(input);
    });

    // 添加到DOM并触发点击
    document.body.appendChild(input);
    input.click();
  }
  function destroyQuill() {
    if (quillEditor.value) {
      console.log('销毁 Quill 实例');
      try {
        // 清理 Quill 相关的 DOM
        if (quillEditor.value.root) {
          quillEditor.value.root.innerHTML = '';
        }
      } catch (error) {
        console.warn('清理 Quill DOM 时出错:', error);
      }
      quillEditor.value = null;
    }
    isQuillReady.value = false;
  }

  // 安全获取编辑器内容的方法
  function getEditorContent() {
    console.log('获取编辑器内容, quillEditor.value:', quillEditor.value);
    console.log('isQuillReady:', isQuillReady.value);

    if (!quillEditor.value) {
      console.error('❌ Quill 实例不存在');
      return null;
    }

    if (typeof quillEditor.value.getContents !== 'function') {
      console.error('❌ quillEditor.value.getContents 不是函数');
      console.log('quillEditor.value 的类型:', typeof quillEditor.value);
      console.log('quillEditor.value 的内容:', quillEditor.value);
      return null;
    }

    try {
      const content = quillEditor.value.getContents();
      console.log('✅ 成功获取编辑器内容:', content);
      return content;
    } catch (error) {
      console.error('❌ 获取编辑器内容时出错:', error);
      return null;
    }
  }

  // 安全的方法获取编辑器实例
  function getQuillInstance() {
    if (!quillEditor.value) {
      console.warn('Quill 实例不存在，尝试重新初始化');
      initQuillWithRetry();
    }
    return quillEditor.value;
  }

  // 基础信息获取
  function getAllUser() {
    get('/solution-ppm/api/v2/built-in-system-ppm/pmgf/get/allUser').then((data) => {
      if (data.code !== 200) {
        showFailToast(data.message);
        return;
      }
      state.allUser = data.data.userDtoList.map((item) => {
        return {
          label: item.name,
          value: item.name,
        };
      });
    });
  }
  function getPmName() {
    get('/solution-ppm-work-order/api/v1/work_order/role/search/PM').then((data) => {
      state.pmNameList = data.data.map((item) => {
        return {
          label: item,
          value: item,
        };
      });
    });
  }
  function getPmo() {
    get('/solution-ppm-work-order/api/v1/work_order/role/search/PMO').then((data) => {
      state.pmoList = data.data.map((item) => {
        return {
          label: item,
          value: item,
        };
      });
    });
  }
  // 区域
  function getAreaList() {
    get('/solution-ppm-work-order/api/v1/work_order/area_info').then((data) => {
      if (data.code !== 200) {
        showFailToast(data.message);
        return;
      }
      state.areaList = data.data.map((item) => {
        return {
          label: item.areaName,
          value: item.areaCode,
        };
      });
    });
  }
  // 项目
  function getProjectList() {
    if (state.modalForm.areaCode) {
      get(
        `/solution-ppm-work-order/api/v1/work_order/project_by_area_code/${state.modalForm.areaCode}`,
      ).then((data) => {
        if (data.code !== 200) {
          showFailToast(data.message);
          return;
        }
        state.projectList = data.data.map((item) => {
          return {
            label: item.projectName,
            value: item.projectId,
          };
        });
      });
    } else {
      get(`/solution-ppm-work-order/api/v1/work_order/project_by_area_code/0`).then((data) => {
        if (data.code !== 200) {
          showFailToast(data.message);
          return;
        }
        state.projectList = data.data.map((item) => {
          return {
            label: item.projectName,
            value: item.projectId,
          };
        });
      });
    }
  }
  // 获取环境
  function getEnvironmentList() {
    if (!state.modalForm.customer) {
      state.environmentList = [];
      return;
    }
    let customerId = state.customList.find((item) => item.label === state.modalForm.customer)?.id;
    get(
      `/solution-ppm-work-order/api/v1/work_order/env?customerId=${customerId ? customerId : ''}`,
    ).then((data) => {
      state.environmentList = data.data.map((item) => {
        return {
          label: item.name,
          value: item.name,
          id: item.id,
        };
      });
    });
  }

  // 产品
  function getProductList() {
    let envId = state.environmentList.find(
      (item) => item.label === state.modalForm.environment,
    )?.id;
    get(`/solution-ppm-work-order/api/v1/work_order/product?envId=${envId ? envId : ''}`).then(
      (data) => {
        state.productList = data.data.map((item) => {
          return {
            label: item.name,
            value: item.name,
            id: item.id,
          };
        });
      },
    );
  }
  // 项目阶段
  function getMilepostList() {
    if (!state.modalForm.projectId) {
      state.milepostList = [];
      return;
    }
    get(
      `/solution-ppm-work-order/api/v1/work_order/milepost_by_project_id/${state.modalForm.projectId}`,
    ).then((data) => {
      if (data.code !== 200) {
        showFailToast(data.message);
        return;
      }
      state.milepostList = data.data.map((item) => {
        return {
          label: item.milepostName,
          value: item.milepostId,
        };
      });
    });
  }

  // 任务
  function getTaskList() {
    if (!state.modalForm.milepostId) {
      state.taskList = [];
      return;
    }
    get(
      `/solution-ppm-work-order/api/v1/work_order/get_by_milepost_id/${state.modalForm.milepostId}`,
    ).then((data) => {
      if (data.code !== 200) {
        showFailToast(data.message);
        return;
      }
      state.taskList = data.data.map((item) => {
        return {
          label: item.taskName,
          value: item.taskId,
        };
      });
    });
  }
  // 客户
  function getCustomerList() {
    get(
      `/solution-ppm-work-order/api/v1/work_order/customer?areaCode=${
        state.modalForm.areaCode ? state.modalForm.areaCode : ''
      }`,
    ).then((data) => {
      if (data.code !== 200) {
        showFailToast(data.message);
        return;
      }
      state.customList = data.data.map((item) => {
        return {
          label: item.name,
          value: item.name,
          areaCode: item.areaCode,
          areaName: item.areaName,
        };
      });
    });
  }
  // 获取告警级别list
  function getWarnList() {
    get(' /solution-ppm-basic-data/api/v1/dictionary/search/GD.GJJB').then((data) => {
      if (data.code !== 200) {
        showFailToast(data.message);
        return;
      }
      state.warnList = data.data.map((item) => {
        return {
          label: item.itemName,
          value: item.itemName,
        };
      });
    });
  }
  // 获取版本
  function getVersionList() {
    let envId = state.environmentList.find(
      (item) => item.label === state.modalForm.environment,
    )?.id;
    let productId = state.productList.find((item) => item.label === state.modalForm.production)?.id;
    get(
      `/solution-ppm-work-order/api/v1/work_order/version?envId=${envId ? envId : ''}&productId=${
        productId ? productId : ''
      }`,
    ).then((data) => {
      state.modalForm.version = data.data;
    });
  }
  // 问题来源
  // 获取问题来源
  function getWtly() {
    get(' /solution-ppm-basic-data/api/v1/dictionary/search/GD.WTLY').then((data) => {
      if (data.code !== 200) {
        showFailToast(data.message);
        return;
      }
      state.wtlyList = data.data.map((item) => {
        return {
          label: item.itemName,
          value: item.itemName,
        };
      });
    });
  }
  // 获取工单类型字典值
  function getWorkType() {
    get(' /solution-ppm-basic-data/api/v1/dictionary/search/GD.GDLX').then((data) => {
      if (data.code !== 200) {
        showFailToast(data.message);
        return;
      }
      state.workTypeList = data.data.map((item) => {
        return {
          label: item.itemName,
          value: item.itemName,
        };
      });
    });
  }
  function getClassfy() {
    get(' /solution-ppm-basic-data/api/v1/dictionary/search_tree/GD.ZRF').then((data) => {
      state.tagList = data.data;
    });
  }
  // 级联
  // 区域变
  function areaChange() {
    state.modalForm.customer =
      state.modalForm.projectId =
      state.modalForm.projectName =
      state.modalForm.environment =
      state.modalForm.production =
      state.modalForm.version =
      state.modalForm.milepostId =
      state.modalForm.milepostName =
      state.modalForm.taskId =
      state.modalForm.taskName =
        undefined;
  }
  // 项目变
  function projectChange() {
    state.modalForm.environment =
      state.modalForm.production =
      state.modalForm.version =
      state.modalForm.milepostId =
      state.modalForm.taskId =
      state.modalForm.taskId =
      state.modalForm.taskName =
        undefined;
  }
  // 项目阶段变
  function milepostChange() {
    state.modalForm.taskId = state.modalForm.taskName = undefined;
  }
  // 环境变
  function environmentChange() {
    state.modalForm.production = state.modalForm.version = undefined;
  }
  // 产品变
  function productChange() {
    state.modalForm.version = undefined;
    getVersionList();
  }
  // 客户改变如果没有选区域自动带区域
  function customerChange() {
    let arae = state.customList.find((item) => item.label === state.modalForm.customer);
    if (arae) {
      state.modalForm.areaCode = arae.areaCode;
      state.modalForm.areaName = arae.areaName;
    }
    state.modalForm.environment = undefined;
  }

  // 保存工单
  //     父工单提交表单
  async function submit() {
    console.log('=== 开始提交 ===');

    // 检查 Quill 是否就绪
    if (!isQuillReady.value || !quillEditor.value) {
      console.warn('Quill 未就绪，尝试重新初始化');
      await initQuill();
    }

    const content = getEditorContent();
    if (!content) {
      console.error('无法获取编辑器内容，停止提交');
      return;
    }

    const quill = getQuillInstance();
    if (!quill) {
      console.error('无法获取编辑器实例');
      return;
    }

    // return
    formRef.value
      .validate()
      .then(async () => {
        state.fatherLoading = true;
        const deltaContent = quillEditor.value.getContents();

        const imageUploadPromises = [];

        deltaContent.ops.forEach((op) => {
          if (op.insert && op.insert.image && op.insert.image.startsWith('data:')) {
            const localSrc = op.insert.image;

            // 如果是 base64 图片，上传并替换为 URL
            const file = dataURLtoFile(localSrc, 'image.png'); // 将 base64 转换为 File 对象

            const uploadPromise = uploadFileAPI(file).then(({ data: { fullUrl } }) => {
              // 替换 op 中的 base64 URL 为服务器返回的 URL
              op.insert.image = fullUrl;
            });

            imageUploadPromises.push(uploadPromise);
          }
        });

        try {
          await Promise.all(imageUploadPromises);
          if (currentData.value.id) {
            // 编辑保存逻辑
            const params = { ...toRaw(state.modalForm) };

            if (params.solverList && params.solverList.length) {
              params.solverList = [params.solverList];
            } else {
              params.solverList = [];
            }

            params.description = JSON.stringify(deltaContent);
            put('/solution-ppm-work-order/api/v1/work_order', params)
              .then((data) => {
                if (data.code !== 200) {
                  showFailToast(data.message);
                  return;
                }
                showSuccessToast(data.message);
                resetFather();
              })
              .finally(() => {
                state.fatherLoading = false;
              });
          } else {
            // 新建保存逻辑
            const params = { ...toRaw(state.modalForm) };

            if (params.solverList && params.solverList.length) {
              params.solverList = [params.solverList];
            } else {
              params.solverList = [];
            }

            console.log(params);
            // return
            params.description = JSON.stringify(deltaContent);
            post('/solution-ppm-work-order/api/v1/work_order', params)
              .then((data) => {
                if (data.code !== 200) {
                  showFailToast(data.message);
                  return;
                }
                showSuccessToast(data.message);
                resetFather();
              })
              .finally(() => {
                state.fatherLoading = false;
              });
          }
        } catch (error) {
          state.fatherLoading = false;
          console.error('图片上传失败', error);
          return; // 终止提交
        }
      })
      .catch((errors) => {
        console.log('校验失败:', errors);
      });
  }
  function resetFather() {
    uni.navigateBack();
  }
  import { showSuccessToast, showFailToast } from 'vant';
  // 取消
  function onCancel() {
    // 通知父组件关闭
    uni.navigateBack();
  }
</script>
<style lang="less" scoped>
  .page_root {
    box-sizing: border-box;
    overflow: hidden !important;
    background-image: url('http://10.40.0.33:9001/file-storage/540302650699495424-source.png') !important;
    background-repeat: no-repeat;
    background-size: cover;
    background-position: center;
  }
  :deep(.u-navbar) {
    background-color: transparent !important;
    padding: 0 40rpx 0 0;
    border: none;
  }
  .add-or-edit-wrapper {
    background-image: url('http://10.40.0.33:9001/file-storage/539780077974796288-source.png');
    background-size: cover;
    height: 100%;
  }
  .form-title {
    font-size: 32rpx;
    color: rgba(0, 0, 0, 0.85);
    font-weight: 600;
    height: 90rpx;
    padding: 24rpx;
    position: relative;
    top: 120rpx;
    margin-bottom: 150rpx;
  }
  /* 滚动内容区域 */
  .form-body {
    height: calc(100vh - 480rpx);
    overflow-y: auto;
    padding: 0 32rpx 32rpx 32rpx;
  }
  .form-body :deep(.u-input) {
    background-color: #fff;
    border-radius: 10rpx;
  }
  .form-body :deep(.u-form-item--left__content__label) {
    color: #979797;
  }
  .top-title {
    text-align: center;
    padding: 10px 16px;
    height: 80rpx;
    font-size: 36rpx;
    font-weight: 600;
    color: #fff;
  }
  /* 固定底部按钮栏 */
  .footer-bar {
    display: flex;
    padding: 0 32rpx;
    gap: 16rpx;
    .van-button {
      flex: 1;
    }
  }
  .quill-editor {
    min-height: 200rpx;
    background: #fff;
  }
  :deep(.ql-toolbar) {
    border-top-left-radius: 20rpx;
    border-top-right-radius: 20rpx;
    border: none;
    background-color: #f3f6ff;
  }
  :deep(.quill-editor) {
    border-bottom-left-radius: 20rpx;
    border-bottom-right-radius: 20rpx;
    background-color: #f3f6ff;
    border: none;
  }
  :deep(.ql-toolbar .ql-formats .ql-bold) {
    border: none !important;
    background: transparent;
  }

  :deep(.ql-toolbar .ql-formats .ql-italic) {
    border: none !important;
    background: transparent;
  }
  :deep(.ql-toolbar .ql-formats .ql-active) {
    background: #dbeafe !important;
  }
  :deep(.ql-toolbar .ql-formats .ql-underline) {
    border: none !important;
    background: transparent;
  }
  :deep(.ql-toolbar .ql-formats .ql-clean) {
    border: none !important;
    background: transparent;
  }
  :deep(.ql-toolbar .ql-image) {
    padding: 0;
    border: none !important;
    background: transparent;
  }
  :deep(.ql-toolbar .ql-formats .ql-picker-label) {
    padding: 0;
    text-align: center;
  }
  :deep(.ql-formats svg) {
    width: 20rpx;
    height: 20rpx;
  }
  :deep(.ql-formats) {
    margin: 0 !important;
  }
  :deep(.van-cell__title) {
    width: 200rpx;
  }
  :deep(.van-toast) {
    z-index: 99999 !important; /* 或者更高的值 */
  }
  .upload-field {
    font-size: 14px;
    color: #323233;
    .label {
      margin-bottom: 10px;
    }
  }
  .editor-wrap {
    font-size: 14px;
    color: #323233;
    .label {
      margin-bottom: 10px;
    }
  }
  .non-image-file a {
    color: #409eff;
    text-decoration: underline;
    cursor: pointer;
  }
  .warp {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100%;
  }
  .rect {
    color: #fff;
  }
  .custom-file-list {
    margin-top: 16px;
  }

  .file-item {
    display: flex;
    align-items: center;
    padding: 12px;
    background: #f7f8fa;
    border-radius: 8px;
    margin-bottom: 8px;
    gap: 12px;
  }

  .file-preview {
    position: relative;
    width: 60px;
    height: 60px;
    border-radius: 6px;
    overflow: hidden;
    cursor: pointer;
    flex-shrink: 0;
  }

  .preview-image {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }

  .file-overlay {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.5);
    display: flex;
    align-items: center;
    justify-content: center;
    opacity: 0;
    transition: opacity 0.3s;
  }

  .file-preview:hover .file-overlay {
    opacity: 1;
  }

  .file-icon {
    width: 60px;
    height: 60px;
    display: flex;
    align-items: center;
    justify-content: center;
    background: #fff;
    border: 1px solid #ebedf0;
    border-radius: 6px;
    cursor: pointer;
    flex-shrink: 0;
    position: relative;
  }

  .icon-wrapper {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 4px;
  }

  .file-type-icon {
    font-size: 24px;
  }

  .download-icon {
    opacity: 0;
    transition: opacity 0.3s;
  }

  .file-icon:hover .download-icon {
    opacity: 1;
  }

  .file-info {
    flex: 1;
    min-width: 0;
  }

  .file-name {
    font-size: 14px;
    color: #323233;
    margin-bottom: 4px;
  }

  .file-size {
    font-size: 12px;
    color: #969799;
  }

  .delete-btn {
    flex-shrink: 0;
  }

  /* 空状态 */
  .file-list-empty {
    text-align: center;
    padding: 40px 20px;
    color: #969799;
    font-size: 14px;
  }
</style>
